/*
 * @Author: za-pangzhongwu
 * @Date: 2018-11-10 11:08:06
 * @Description: ''
 * @Last Modified by: zoushiyong
 * @Last Modified time: 2018-11-26 11:19:27
 * @ToDo: ''
 */

import React, { Component } from 'react'
import { message, Row, Col, Button, Modal, Table, Form, Input } from 'antd'
import { connect } from 'mirrorx'
import api from '../../../api/index'
import Estabbish from './AddSubAccount'
import ChangePassword from './ChangePassword'

const FormItem = Form.Item

class SubMgmt extends Component {
  constructor (props) {
    super(props)
    this.state = {
      showModal: false, // 控制点击 New Sub-account 功能模块的显示隐藏
      visible: false, // 控制点击 Edit 功能模块的显示隐藏
      addSucceed: false, // 成功添加子账号弹框
      deleteModel: false, // 删除框显示隐藏
      roleId: '', // 存出角色Id用于删除
      role: '', // 帮子组件传输Role
      roles: '',
      removeData: '',
      rowsdata: [],
      childerName: '',
      childerEmail: '',
      pageTotal: 1, // 总页数
      current: 1, // 当前页    初始化
      pageSize: 10, // 每页数据量
      dataSource: [],
      menuAuth: false
    }
    // 创建权限弹框显示
    this.showEsmodal = this.showEsmodal.bind(this)
    // 修改密码弹框显示
    this.showPsmodal = this.showPsmodal.bind(this)
    // 隐藏权限弹框
    this.hideModal = this.hideModal.bind(this)
    // 清空输入框内容
    this.onEmpty = this.onEmpty.bind(this)
    // 用于接收子组件修改数据信息后的数据
    this.dataCycle = this.dataCycle.bind(this)
    // 查询子账户数据信息
    this.queryAccount = this.queryAccount.bind(this)
    // 输入框change时间实时赋值
    this.newInputData = this.newInputData.bind(this)
    // 获取页码信息
    this.onCurrent = this.onCurrent.bind(this)
    // 获取子组件的角色列表
    this.roleStare = this.roleStare.bind(this)
    // 修改密码成功弹窗
    this.success = this.success.bind(this)
    // 确认删除
    this.confirmDelete = this.confirmDelete.bind(this)
    // 取消删除
    this.cancel = this.cancel.bind(this)
    // 删除成功
    this.deleteSuccess = this.deleteSuccess.bind(this)
    // 匹配正则
    this.inputSky = this.inputSky.bind(this)
  }
  inputSky (rule, value, callbackFun) {
    if (value === '') {
      callbackFun('Please input user name')
    } else if (/^\s+|\s+$/.test(value)) {
      callbackFun('Please input valid user name address')
    } else {
      callbackFun()
    }
  }
  // 组件挂在前发送查询账户请求
  componentDidMount () {
    this.queryAccount()
  }
  hideModal () {
    this.setState({
      visible: false,
      showModal: false,
      addSucceed: false,
      roleList: []
    })
  }

  showPsmodal (key, roleId, role) {
    this.setState({ visible: true, roles: key, roleId: roleId, role: role })
    T.ajax({
      url: api.getRolesByPartnerId.path,
      method: 'GET',
      loading: true
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          roleList: res.data
        })
      }
    })
  }
  showEsmodal () {
    T.ajax({
      url: api.getRolesByPartnerId.path,
      method: 'GET',
      loading: true
    }).then(res => {
      this.setState({
        showModal: true,
        roleList: res.data
      })
    })
  }

  cancel () { this.setState({ deleteModel: false }) }

  dataCycle (dataList) { this.setState({ dataSource: dataList }) }

  confirmDelete () {
    const dataSource = [...this.state.dataSource]
    // 将删除的子账户信息发送至后台
    const deleteSub = dataSource.filter(item => item.key === this.state.roleId)[0].key
    T.ajax({
      url: api.deleteSubAccountById.path,
      loading: true,
      data: { 'userId': deleteSub }
    }).then(res => {
      if (res.code === 0) {
        if (this.state.dataSource.length === 1) {
          this.setState({
            current: this.state.current - 1
          })
        }
        this.queryAccount() // 重新加载数据
        this.setState({ deleteModel: false })
      }
      this.deleteSuccess()
    })
  }
  deleteSuccess () {
    message.success(' Sub-account delete successfully. ')
  };
  success () {
    Modal.success({
      title: ' Edit Successful',
      content: 'The sub-account has been successfully edited.'

    })
  }
  onCurrent (pageNumber) {
    this.setState({
      current: pageNumber.current
    }, () => {
      this.queryAccount()
    })
  }
  queryAccount (str) { // 获取列表多处需使用，进行简单封装
    const { current, pageSize } = this.state
    T.ajax({
      url: api.getSubAccounts.path, // 1.子账户列表渲染
      loading: true,
      data: {
        'condition': {
          'nickName': str ? this.state.childerName : '',
          'email': str ? this.state.childerEmail : ''
        },
        'pageIndex': current,
        'pageSize': pageSize
      }
    }).then(res => {
      const { rows, pageTotal } = res.data
      let dataList = []
      if (res.code === 0) {
        for (let i = 0; i < rows.length; i++) {
          dataList.push({// 循环后台数据
            'roleId': rows[i].roleId,
            'key': rows[i].id,
            'User': rows[i].nickName,
            'Role': rows[i].roleName,
            'Sign in account': rows[i].email
          })
        }
      }
      this.setState({
        rowsdata: rows,
        pageTotal: pageTotal,
        dataSource: dataList
      })
    })
    console.log(this.state.dataSource)
  }
  onEmpty () { // 清空表单后重载数据
    this.props.form.resetFields()
    this.setState({ childerName: '', childerEmail: '' })
    this.queryAccount()
  }
  newInputData (e, change) {
    e.preventDefault()
    if (arguments[1] === 'email') {
      this.setState({ childerEmail: e.target.value })
    } else if (arguments[1] === 'User') {
      this.setState({ childerName: e.target.value })
    }
  }
  render () {
    const { dataSource, showModal, role, visible, pageTotal, roleList, pageSize, roles, roleId } = this.state
    const { handleChildChange } = this.props
    const { getFieldDecorator } = this.props.form
    const pagination = {
      total: pageTotal * pageSize,
      pageSize: pageSize,
      showQuickJumper: true,
      onShowSizeChange: (current, size) => {
      }
    }
    let { grantedMenus } = this.props
    let menuAuth = false
    if (grantedMenus) {
      menuAuth = T.getMenuAuth('Account Management', grantedMenus)
    }
    let columns = [{
      title: 'User',
      dataIndex: 'User',
      width: '30%'
    }, {
      title: 'Role',
      dataIndex: 'Role'
    }, {
      title: 'Sign in account',
      dataIndex: 'Sign in account'
    }, {
      title: 'Operations',
      dataIndex: 'Operations',
      render: (text, record) => {
        return (
          this.state.dataSource.length > 0
            ? (
              <div>
                <a
                  href='#'
                  disabled={!menuAuth}
                  onClick={() => menuAuth && this.setState({ deleteModel: true, roleId: record.key })}>Delete</a>
                <span className='ml10 font-gap'>|</span>
                <a
                  className='ml10'
                  href='#'
                  disabled={!menuAuth}
                  onClick={(key) => this.showPsmodal(record.key, record.roleId, record.Role)}>Edit</a>
              </div>
            ) : null
        )
      }
    }]

    return (
      <Row>
        <div className='account-antd'>
          <Form layout='inline' className='mb18'>
            <Col span='24' className='search-panel'>
              <Row>
                <Col span={8}>
                  <FormItem
                    label='Sign in account'>
                    {getFieldDecorator('email', {
                      rules: [{ message: 'Please input valid email address', pattern: /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g }]
                    })(
                      <Input placeholder='Please input' onChange={(e) => { this.newInputData(e, 'email') }} />
                    )}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem
                    label='User'>
                    {getFieldDecorator('userName', {
                      rules: [{ message: 'Please enter the correct user name' }, {
                        validator: this.inputSky
                      }]
                    })(
                      <Input placeholder='Please input' onChange={(e) => { this.newInputData(e, 'User') }} maxLength='50' />
                    )}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem>
                    <Button type='primary' htmlType='submit' onClick={() => this.queryAccount('Search')}>Search</Button>
                    <Button type='primary' className='ml30' onClick={this.onEmpty}>Reset</Button>
                    <Button
                      type='primary'
                      className='ml30'
                      icon='plus'
                      disabled={!menuAuth}
                      onClick={this.showEsmodal}>New Sub-account</Button>
                  </FormItem>
                </Col>
              </Row>
              {
                roleList
                  ? <div>
                    <Estabbish
                      roleList={roleList}
                      showModal={showModal}
                      hideModal={this.hideModal}
                      queryAccount={this.queryAccount}
                      handleChildChange={handleChildChange}
                    />
                    <ChangePassword
                      roleList={roleList}
                      role={role}
                      visible={visible}
                      handleSubmit={this.handleSubmit}
                      hideModal={this.hideModal}
                      queryAccount={this.queryAccount}
                      success={this.success}
                      roleId={roleId}
                      roles={roles}
                    />
                  </div>
                  : ''
              }
            </Col>
          </Form>
          <Col span='24' className='rolelist'>
            <Table
              bordered
              dataSource={dataSource}
              pagination={pagination}
              columns={columns}
              menuAuth={menuAuth}
              onChange={this.onCurrent} />
          </Col>
          <Modal
            title='Delete'
            className='delete-role-zou'
            centered
            visible={this.state.deleteModel}
            okText='Confirm'
            cancelText='Cancel'
            onOk={this.confirmDelete}
            onCancel={this.cancel}
          >
            <p>Are you sure you want to delete this sub-account?</p>
          </Modal>
        </div>
      </Row>
    )
  }
}
const SubMgmtForm = Form.create()(SubMgmt)

export default connect(state => {
  return state.menuModel
})(SubMgmtForm)
